package com.oscar.ehome.utils.upload;

import android.graphics.BitmapFactory;
import android.util.Log;

import com.oscar.ehome.utils.util.AesUtils;
import com.oscar.ehome.utils.util.BitmapCompressor;
import com.oscar.ehome.utils.util.makeTime;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.util.concurrent.CountDownLatch;

/**
 * Created by juxing
 * author: MengWanhe
 * date: On 2017/8/17
 */

public class UploadFile implements Runnable {
    private CountDownLatch downLatch;//计数器
    private String fileName;//文件名
    private OnThreadResultListener listener;//任务线程回调接口
    private int percent = 0;//进度
    String path;
    String keyRand;
    String token;


    public UploadFile(CountDownLatch downLatch, String fileName, String token, OnThreadResultListener listener) {
        this.downLatch = downLatch;
        this.fileName = fileName;
        this.listener = listener;
        this.token = token;
        SaveFeedback();
    }

    @Override
    public void run() {
//        SaveFeedback();
    }
    ///七牛上传图片
    private void SaveFeedback() {
        final byte[] bytes = BitmapCompressor.compressbyte(BitmapFactory.decodeFile(fileName), 10240);
        //初始化
        Configuration config = new Configuration.Builder()
                .connectTimeout(100) // 链接超时。默认100秒
                .responseTimeout(160) // 服务器响应超时。默认60秒
                .build();
        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        final UploadManager uploadManager = new UploadManager();

        int v = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;//产生1000-9999的随机数;

        try {
            final String mtime = makeTime.mtime();
            Log.d("mwh", "mtime" + mtime);
            keyRand = v + mtime;
        } catch (Exception e) {
            e.printStackTrace();
        }
        new Thread() {
            public void run() {
                String key = keyRand;
                uploadManager.put(bytes, key, token,
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                //res包含hash、key等信息，具体字段取决于上传策略的设置
                                if (info.isOK()) {
                                    listener.onFinish(key);//顺利完成

                                } else {
                                    listener.onInterrupted();//被中断
                                }
                                Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                            }
                        }, null);
            }

        }.start();
    }

}
